package com.industry.system.service.impl;

import cn.dev33.satoken.stp.SaTokenInfo;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.google.gson.Gson;
import com.industry.framework.common.constant.Global;
import com.industry.framework.common.redis.RedisUtils;
import com.industry.framework.common.utils.RSAUtils;
import com.industry.system.dal.dataobject.SystemUser;
import com.industry.system.dal.db.AuthBizMapper;
import com.industry.system.dal.db.SystemUserMapper;
import com.industry.system.satoken.StpContextHelper;
import com.industry.system.service.AuthService;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.Serializable;
import java.util.List;

@Service
public class AuthServiceImpl implements AuthService {
    @Resource
    private SystemUserMapper systemUserMapper;
    @Resource
    private AuthBizMapper authBizMapper;
    @Value("${safe.time}")
    private long safeTime;

    @Override
    public SaTokenInfo doLogin(String userName, String pwd) {
        SystemUser systemUser = systemUserMapper.selectOne(
                new LambdaQueryWrapper<SystemUser>()
                        .eq(SystemUser::getUserName, userName)
        );
        if (systemUser == null) {
            return null;
        }
        String decryptPwd = RSAUtils.decrypt(systemUser.getPassword());
        if (!StrUtil.equals(decryptPwd, pwd)) {
            return null;
        }
        StpUtil.login(systemUser.getId());
        StpContextHelper.setUserInfo(systemUser);
        return StpUtil.getTokenInfo();
    }

    @Override
    public SystemUser getUserInfo() {
        SaTokenInfo tokenInfo = StpUtil.getTokenInfo();
        if (tokenInfo != null && tokenInfo.isLogin) {
            //TODO 获取权限和角色  暂时先这么写，这个后期需要改一下
            List<String> menuPermission = authBizMapper.getMenuPermission(Long.parseLong((String) tokenInfo.getLoginId()));
            String key = Global.authPermissionPrefix + ":" + tokenInfo.getLoginId();
            RedisUtils.setCacheObject(key, menuPermission);
            List<String> roleList = authBizMapper.getRoleList(Long.parseLong((String) tokenInfo.getLoginId()));
            key = Global.authRolePrefix + ":" + tokenInfo.getLoginId();
            RedisUtils.setCacheObject(key, new Gson().toJson(roleList));

            return systemUserMapper.selectById((Serializable) tokenInfo.getLoginId());
        }
        return null;
    }

    @Override
    public boolean openSafe(String pwd) {
        SystemUser systemUser = getUserInfo();
        // 比对密码
        if (systemUser != null && StrUtil.equals(RSAUtils.decrypt(systemUser.getPassword()), pwd)) {
            // 比对成功，为当前会话打开二级认证，有效期为safeTime秒
            StpUtil.openSafe(safeTime);
            return true;
        }
        return false;
    }
}
